package com.agent.web;

import com.agent.entity.CourseSchedule;
import com.agent.service.CourseScheduleService;
import com.agent.utils.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/web/courses")
@RequiredArgsConstructor
public class CourseScheduleController {

    private final CourseScheduleService courseScheduleService;

    // 导入课程表
    @PostMapping("/import")
    public List<CourseSchedule> importCourseSchedule(@RequestParam("file") MultipartFile file) {
        return courseScheduleService.importCourseSchedule(file);
    }

    // 查询课程列表（支持按星期与时间段筛选）
    @GetMapping("/list")
    public ResponseEntity<?> list(@RequestParam(required = false) Integer dayOfWeek,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        System.out.println("查询页码：" + page + "，查询数量：" + size);
        Page<CourseSchedule> pageParam = new Page<>(page, size);
        // 构建筛选你条件
        LambdaQueryWrapper<CourseSchedule> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseSchedule::getUserId, userId);
        if (dayOfWeek != null) {
            qw.eq(CourseSchedule::getDayOfWeek, dayOfWeek);
        }
        // 时间筛选
        LocalTime st = null;
        LocalTime et = null;
        try { if (startTime != null && !startTime.isBlank()) st = LocalTime.parse(startTime); } catch (Exception ignored) {}
        try { if (endTime != null && !endTime.isBlank()) et = LocalTime.parse(endTime); } catch (Exception ignored) {}
        if (st != null && et != null) {
            qw.lt(CourseSchedule::getStartTime, et)
              .gt(CourseSchedule::getEndTime, st);
        } else if (st != null) {
            qw.ge(CourseSchedule::getEndTime, st);
        } else if (et != null) {
            qw.le(CourseSchedule::getStartTime, et);
        }
        qw.orderByAsc(CourseSchedule::getDayOfWeek, CourseSchedule::getStartTime);
        // 分页+筛选
        Page<CourseSchedule> result = courseScheduleService.page(pageParam, qw);
        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", result.getRecords());
        resp.put("total", result.getTotal());
        resp.put("current", result.getCurrent());
        resp.put("size", result.getSize());
        resp.put("pages", result.getPages());
        return ResponseEntity.ok(resp);
    }

    // 课程详情
    @GetMapping("/detail/{id}")
    public ResponseEntity<?> detail(@PathVariable("id") Long id) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        CourseSchedule cs = courseScheduleService.getById(id);
        if (cs == null || !userId.equals(cs.getUserId())) {
            resp.put("code", 404);
            resp.put("msg", "Course not found");
            return ResponseEntity.status(404).body(resp);
        }
        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", cs);
        return ResponseEntity.ok(resp);
    }

    // 创建课程
    @PostMapping("/create")
    public ResponseEntity<?> create(@RequestBody CourseSchedule req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        // 仅接受允许的字段
        CourseSchedule entity = CourseSchedule.builder()
                .userId(userId)
                .courseName(req.getCourseName())
                .teacher(req.getTeacher())
                .location(req.getLocation())
                .dayOfWeek(req.getDayOfWeek())
                .workWeek(req.getWorkWeek())
//                .startTime(req.getStartTime())
//                .endTime(req.getEndTime())
                .build();

        boolean ok = courseScheduleService.save(entity);
        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "create failed");
        resp.put("data", entity.getId());
        return ResponseEntity.ok(resp);
    }

    // 更新课程
    @PutMapping("/update/{id}")
    public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody CourseSchedule req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        CourseSchedule cs = courseScheduleService.getById(id);
        if (cs == null || !userId.equals(cs.getUserId())) {
            resp.put("code", 404);
            resp.put("msg", "Course not found");
            return ResponseEntity.status(404).body(resp);
        }
        if (req.getCourseName() != null) cs.setCourseName(req.getCourseName());
        if (req.getTeacher() != null) cs.setTeacher(req.getTeacher());
        if (req.getLocation() != null) cs.setLocation(req.getLocation());
        if (req.getDayOfWeek() != null) cs.setDayOfWeek(req.getDayOfWeek());
        if (req.getWorkWeek() != null) cs.setWorkWeek(req.getWorkWeek());
        if (req.getStartTime() != null) cs.setStartTime(req.getStartTime());
        if (req.getEndTime() != null) cs.setEndTime(req.getEndTime());

        boolean ok = courseScheduleService.updateById(cs);
        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "update failed");
        return ResponseEntity.ok(resp);
    }

    // 删除课程
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> delete(@PathVariable("id") Long id) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        CourseSchedule cs = courseScheduleService.getById(id);
        if (cs == null || !userId.equals(cs.getUserId())) {
            resp.put("code", 404);
            resp.put("msg", "Course not found");
            return ResponseEntity.status(404).body(resp);
        }
        boolean ok = courseScheduleService.removeById(id);
        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "delete failed");
        return ResponseEntity.ok(resp);
    }

}